package com.yifi.common.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;

import com.auth0.jwt.interfaces.Claim;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.yifi.common.base.ApiController;
import com.yifi.common.base.BaseController;
import com.yifi.common.model.AjaxResult;
import com.yifi.common.model.Syslog;
import com.yifi.common.utils.JWTUtils;
import com.yifi.common.utils.StringUtils;

import cn.hutool.core.util.StrUtil;

public class JwtTokenInterceptor implements Interceptor {

	private static final Logger logger = Logger.getLogger(JwtTokenInterceptor.class);  
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		String contenttype = controller.getRequest().getHeader("content-type");	//获取当前Controller的token
		
		String token = controller.getRequest().getParameter("token");		//获取参数，如果没有参数再在请求头中获取Authorization参数
		if(StrUtil.isEmpty(token))
		{
			token =	controller.getRequest().getHeader("Authorization");	//获取当前Controller的token
		}
		
		if(StrUtil.isEmpty(token))
		{
			logger.info("未登录");
			inv.getController().redirect("/login");
		}
		else
		{
			try {
                Map<String, Claim> map = JWTUtils.verifyToken(token);    // 该方法验证失败会抛出异常
                String id = map.get("id").asString();                         // 没有id也会抛出异常
                controller.getRequest().setAttribute("id", id);                         // 传递参数id
                logger.info("登录成功");
				inv.invoke();
            } catch (Exception e) {                                     // 抛出异常进行跳转
            	//controller.getRequest().getRequestDispatcher("/user/need_login.do").forward(request, response);
                controller.renderJson(AjaxResult.error("错误或者失效token"+e.toString()));
            	logger.info("登录过期");
            }
		}

		//集成于 BaseController 类的 controller 才可以 执行下边的 日志记录操作
		if(ApiController.class.isAssignableFrom(controller.getClass()))
		{
			ApiController Bcontroller = (ApiController)controller;
			Syslog reqSysLog = Bcontroller.getAttr("reqSysLog");
			//Bcontroller.setReqSysLog(reqSysLog,JWTUtils.getAppUID(token));
			reqSysLog.setSyslog("1"); // 指定日志是否入库
		}
	}

}
